﻿using QDasConverter.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindGoes6.Database; 

namespace QDasConverter.Forms
{
    public partial class RangeForm : Form
    {
        IniAccess ia = new IniAccess("config.ini");

        public RangeForm()
        {
            InitializeComponent();
        }

        public void UpdateIDs()
        {
            DBManager dm = new DBManager();

            dm.CommandText = "SELECT TOP (1) ID, [DateTime] FROM spc_spcdata order by ID desc";
            var data1 = dm.GetRow();
            string idstr = data1 != null && data1.Length > 0 ? data1[0] : "0";
            lbInfo.Text = "最新记录：";
            lbInfo.Text += data1 != null && data1.Length > 0 ? string.Join(",", data1) : "";

            DateTime dt = dtStartDate.Value;
            lbIDs.Items.Clear();
            string sql = "SELECT TOP (1) ID FROM spc_spcdata Where [DateTime] > '$date$'  order by SPCID desc";
            for (int i = 0; i < 7; i++)
            {
                string date = dt.AddDays(i).ToString("yyyy-MM-dd");
                dm.CommandText = sql.Replace("$date$", date);
                var data = dm.GetRow();
                string id = data == null || data.Length == 0 ? idstr : data[0];
                lbIDs.Items.Add(date + ": " + id);
            }


        }

        private void RangeForm_Load(object sender, EventArgs e)
        {
            string cs = Common.Decrypt(ia.ReadValue("cs"));
            if (!string.IsNullOrEmpty(cs))
            {
                DBManager.ConnectionString = cs;
            }
            UpdateIDs();


            try
            {
                nudCurrentID.Value = int.Parse(ia.ReadValue("LastID"));
            }
            catch
            {
                nudCurrentID.Value = 0;
            }

            try
            {
                nudBatchCount.Value = int.Parse(ia.ReadValue("BatchCount"));
            }
            catch
            {
                nudCurrentID.Value = 10;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UpdateIDs();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            ia.WriteValue("LastID", nudCurrentID.Value.ToString());
            ia.WriteValue("BatchCount", nudBatchCount.Value.ToString());
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
